package performance

import (
	"fmt"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"time"
)

// CostPoint 耗时点位信息
type CostPoint struct {
	name string
	t    time.Time
}

func NewCostPoint(name string, ts ...time.Time) *CostPoint {
	t := time.Now()
	if len(ts) > 0 {
		t = ts[0]
	}
	return &CostPoint{
		name, t,
	}
}

// BatchPointCostPrinter 批量点位耗时打印
type BatchPointCostPrinter struct {
	v1log.InvokeLog
	arr []*CostPoint
}

func NewBatchPointCostPrinter() *BatchPointCostPrinter {
	return &BatchPointCostPrinter{
		arr: []*CostPoint{NewCostPoint("start")},
	}
}

func (printer *BatchPointCostPrinter) Print(id string, ts ...*CostPoint) {
	if id == "" {
		id = fmt.Sprint(time.Now().UnixNano())
	}
	if len(ts) == 0 {
		ts = printer.arr
	}
	for i, p := range ts {
		cost := time.Duration(0)
		if i > 0 {
			cost = ts[i].t.Sub(ts[i-1].t)
		}
		printer.Info("%s point-%s cost %s, %s", id, p.name, cost, p.t)
	}
}

func (printer *BatchPointCostPrinter) AddPoint(name string) {
	printer.arr = append(printer.arr, NewCostPoint(name, time.Now()))
}
